package com.atguigu.gulimallseckill.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.to.SeckillSessionSkuTo;
import com.atguigu.common.to.seckill.RedisSeckillTo;
import com.atguigu.common.to.seckill.SkuInfoTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimallseckill.feign.CouponFeignService;
import com.atguigu.gulimallseckill.feign.ProductFeignService;
import com.atguigu.gulimallseckill.interceptor.LoginInterceptor;
import com.atguigu.gulimallseckill.service.SeckillService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {
    private final String SESSION_PREFIX ="seckill:sessions:";
    private final String SECKILL_CACHE_PREFIX ="seckill:skus";
    private final String SKU_STOCK_SEMAPHORE ="seckill:stock:";
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void uploadSeckillSkuLatest3Days() {
        System.out.println("++++++++++++++++");
        //查询近3天所有的优惠活动
        R r = couponFeignService.getSeckillSessionList3Days();
        if (r.getCode()==0){
            //调用成功
            List<SeckillSessionSkuTo> data = r.getData(new TypeReference<List<SeckillSessionSkuTo>>() {});
            System.out.println("接口返回信息"+data);
            saveSessionInfos(data);
            saveSessionSkus(data);
        }

    }

    /**
     * 获取当前时间段秒杀的商品
     * @return
     */
    @Override
    public List<RedisSeckillTo> getSeckillSkus() {
        long time = new Date().getTime();
        Set<String> keys = stringRedisTemplate.keys(SESSION_PREFIX + "*");
        if (keys.size()>0){
            for (String key : keys) {
                String replace = key.replace(SESSION_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.valueOf(s[0]);
                Long end = Long.valueOf(s[1]);
                if (start<=time&&end>=time){
                    List<String> range = stringRedisTemplate.opsForList().range(key, 0, -1);
                    BoundHashOperations<String, String , Object> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
                    List<Object> objects = hashOps.multiGet(range);
                   if (objects.size()>0){
                       List<RedisSeckillTo> collect = objects.stream().map(item -> {
                           RedisSeckillTo redisSeckillTo = JSON.parseObject((String) item, RedisSeckillTo.class);
                           return redisSeckillTo;
                       }).collect(Collectors.toList());
                       return collect;
                   }
                    break;
                }
            }
        }
        return null;
    }

    @Override
    public RedisSeckillTo getSeckillSkuInfo(Long skuId) {
        BoundHashOperations<String, String , String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        if (hashOps.keys().size()>0){
            for (String key : hashOps.keys()) {
                if (!key.isEmpty()){
                    String[] s = key.split("_");
                    if (s[1].equals(skuId.toString())){
                        String data = hashOps.get(key);
                        RedisSeckillTo redisSeckillTo = JSON.parseObject(data, RedisSeckillTo.class);
                        Long startTime = redisSeckillTo.getStartTime();
                        Long endTime = redisSeckillTo.getEndTime();
                        Long time = new Date().getTime();
                        if (startTime<=time&&endTime>=time){

                        }else {
                            redisSeckillTo.setRandomCode(null);
                        }
                        return redisSeckillTo;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        //校验秒杀合法性
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        String s = hashOps.get(key);
        if (StringUtils.isEmpty(s)){
            return null;
        }else {
            RedisSeckillTo redisSeckillTo = JSON.parseObject(s, RedisSeckillTo.class);
            //校验时间是否在秒杀时间段内
            Long time = new Date().getTime();
            Long ttl = redisSeckillTo.getEndTime() -  time;
            if (time>=redisSeckillTo.getStartTime()&&time<=redisSeckillTo.getEndTime()){
                String randomCode = redisSeckillTo.getRandomCode();
                //校验随机码
                if (randomCode.equals(key)){
                    //校验购买数量
                    if (num<=redisSeckillTo.getSeckillLimit()){
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(killId, num.toString(),ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean){
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                                try {
                                    boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                    if (b){
                                        //进行秒杀
                                        String timeId = IdWorker.getTimeId();
                                        SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                        seckillOrderTo.setOrderSn(timeId);
                                        MemberEntityVo memberEntityVo = (MemberEntityVo) LoginInterceptor.threadLocal.get();
                                        seckillOrderTo.setMemberId(memberEntityVo.getId());
                                        seckillOrderTo.setNum(num);
                                        seckillOrderTo.setSkuId(redisSeckillTo.getSkuId());
                                        seckillOrderTo.setPromotionSessionId(redisSeckillTo.getPromotionSessionId());
                                        seckillOrderTo.setSeckillPrice(redisSeckillTo.getSeckillPrice());
                                        rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                                        return timeId;
                                    }
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }

                        }else {
                            return null;
                        }
                    };
                }else {
                    return null;
                }
            }else {
            }
            return null;
        }
    }

    private void saveSessionSkus(List<SeckillSessionSkuTo> skuTos) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
    if (skuTos.size()>0){
        skuTos.forEach(sessions->{
            sessions.getRelationSkus().stream().forEach(item->{
                Long key = item.getSkuId();
                if (!hashOps.hasKey(item.getPromotionSessionId()+"_"+key.toString())){
                    RedisSeckillTo redisSeckillTo = new RedisSeckillTo();

                    R r = productFeignService.info(item.getSkuId());
                    if (r.getCode()==0){
                        //设置商品信息
                        SkuInfoTo data = r.getData("skuInfo",new TypeReference<SkuInfoTo>() {});
                        redisSeckillTo.setSkuInfoTo(data);
                    }
                    //设置当前活动的开始时间和结束时间
                    redisSeckillTo.setStartTime(sessions.getStartTime().getTime());
                    redisSeckillTo.setEndTime(sessions.getEndTime().getTime());
                    //设置随机码
                    String token = UUID.randomUUID().toString().replace("-", "");
                    redisSeckillTo.setRandomCode(token);
                    BeanUtils.copyProperties(item,redisSeckillTo);
                    //设置信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(redisSeckillTo.getSeckillCount());

                    //提交数据到redis
                    String jsonString = JSON.toJSONString(redisSeckillTo);
                    hashOps.put(item.getPromotionSessionId()+"_"+key.toString(),jsonString);
                }

            });
        });
    }
    }

    private void saveSessionInfos(List<SeckillSessionSkuTo> sessions) {
        if (sessions.size()>0&&sessions!=null){
            sessions.forEach(item->{
                long start = item.getStartTime().getTime();
                long end = item.getEndTime().getTime();
               if (!stringRedisTemplate.hasKey(SESSION_PREFIX+start+"_"+end)){
                   String key = SESSION_PREFIX+start+"_"+end;
                   List<String> collect = item.getRelationSkus().stream().map(sku -> sku.getPromotionSessionId()+"_"+sku.getSkuId().toString()).collect(Collectors.toList());
                   stringRedisTemplate.opsForList().leftPushAll(key,collect);
               }
            });
        }
    }

}
